#!/usr/bin/env python

import argparse
import imp
import logging
import os
import pipes
import subprocess
import sys

import common

root_dir = common.root_dir
runtime_tools_dir = common.runtime_tools_dir
build_dir = common.build_dir
source_dir = common.source_dir
tmp_dir = common.tmp_dir
script_dir = os.path.join(source_dir, 'profiler/osx-profiler/scripts')

logger = logging.getLogger(os.path.basename(__file__))

def main(stack):
    cmd = ( 'pgrep', '-x', 'Instruments' )
    returncode = int(subprocess.call(cmd, env=os.environ, stdout=subprocess.PIPE))
    if not returncode:
        print('Please close Instruments before running profiler.')
        exit(0)

    remainder = common.separateBinaryArgs()

    parser = argparse.ArgumentParser(
        description='Profile a Skip program',
        parents=[common.commonArguments()])
    parser.add_argument('--tool', '-t', default='Time Profiler',
        type=lambda x: x.lower(),
        choices=["time profiler", "allocations", "leaks"],
        help='Profiling tool to run ("time profiler", "allocations", "leaks")')
    args = common.parse_args(parser)

    programDir, programUnit = args.program
    program = '/:'.join(args.program)

    output = stack.enter_context(common.tmpfile(delete=False, name=programUnit))
    output.close()

    if args.exists and not os.path.exists('/'.join(args.program)):
        exit('Properly named executable does not exist for: ' + program)

    target = os.path.abspath(program)
    flags = ' '.join(remainder)
    cwd = ''

    if not args.exists:
        # compile the skip program
        print_skip_to_llvm = ('--print-skip-to-llvm',) if args.compiler else ()

        cmd = (
            os.path.join(runtime_tools_dir, 'compile'),
            '--output', output.name,
            program) + print_skip_to_llvm

        logger.debug('Running: ' + ' '.join(map(pipes.quote, cmd)))

        if args.compiler:
            cwd = os.path.dirname(target)
            target, flags = subprocess.check_output(cmd).strip().split('\n')[-2:]
        else:
            print('Compiling...')
            common.callHelper(cmd)
            target = os.path.abspath(output.name)

    # execute applescript through osascript
    cmd = (
        os.path.join(script_dir, 'open_profiler'),
        args.tool,
        target,
        flags,
        cwd)

    # just a little spinner to make sure the user knows it's running...
    print('Stop touching your mouse and keyboard while we are opening the profiler.')
    with common.Spinner() as spinner:
        logger.debug('Running: ' + ' '.join(map(pipes.quote, cmd)))
        spinner.start()
        common.callHelper(cmd)
        spinner.stop()

    print('You can now resume using your keyboard and mouse.')

if __name__ == '__main__':
    with common.ExitStack() as stack:
        main(stack)
